from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from pyquery import PyQuery as pq
import re
from config import *
import pymongo

client=pymongo.MongoClient(MONGO_URL)
db=client[MONGO_DB]

brower=webdriver.PhantomJS(service_args=SERVICES_ARGS)
wait=WebDriverWait(brower,10)

brower.set_window_size(1400,900)

def search():
    print('正在搜索')
    try:
        brower.get('https://www.taobao.com')
        input=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#q')))
        submit=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#J_TSearchForm > div.search-button > button')))
        input.send_keys('美食')
        submit.click()
        total=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.total')))
        getProducts()
        return total.text
    except TimeoutException:
        return search()

def nextPage(pageNum):
    print('正在翻页： ',pageNum)
    try:
        input=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.form > input')))
        submit=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit')))
        input.clear()
        input.send_keys(pageNum)
        submit.click()
        wait.until(EC.text_to_be_present_in_element(
            (By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),
        str(pageNum)))
        getProducts()
    except TimeoutException:
        nextPage(pageNum)

def getProducts():
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item')))
    html=brower.page_source
    doc=pq(html)
    items=doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        #image=item.find('.pic .img')
        product={
            'image':item.find('.pic .img').attr('data-src'),
            'price':item.find('.price').text(),
            'deal':item.find('.deal-cnt').text()[:-3],
            'title':item.find('.title').text(),
            'shop':item.find('.shop').text(),
            'location':item.find('.location').text()
        }
        #print("11:    ",image)
        print(product)
        saveToMongo(product)

def saveToMongo(result):
    try:
        if db[MONGO_TABLE].insert(result):
            print("保存数据库成功")
    except Exception:
        print('保存数据库失败',result)

def main():
    total=search()
    total=int(re.compile('(\d+)').search(total).group(1))
    for i in range(2,total+1):
        nextPage(i)
    brower.close()


if __name__ =='__main__':
    main()